package arithmetic;

/**
 * @Author: Jie
 * @Date: 2019/3/7 11:19
 * @Function :
 * 思路：map 每个node
 * 1.包含 isWord
 * 2.下一层的节点 node[] .
 * 3. value
 *  value可以用node[index] 表示。
 *  node[index]==null，value 没有值。否则有值。 index 就是value。
 *
 *
 * @see arithmetic.A_18_Trie
 * @see arithmetic.A_19_TrieSearchWorld
 */
class Trie {
    private class TrieNode{
        private boolean isWord;
        private TrieNode[] childrenNode = new TrieNode[256];
        private TrieNode() {
        }
    }

    private TrieNode root;
    /** Initialize your data structure here. */
    public Trie() {
        root = new TrieNode();
    }

    /** Inserts a word into the trie. */
    public void insert(String word) {
        TrieNode currentTempNode = root;
        char[] chars = word.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            char index = chars[i];
            if ( currentTempNode.childrenNode[index] == null){
                TrieNode trieNode = new TrieNode();
                currentTempNode.childrenNode[index] = trieNode;
            }
            currentTempNode = currentTempNode.childrenNode[index];
        }
        currentTempNode.isWord = true;
    }

    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        TrieNode currentTempNode = root;
        char[] chars = word.toCharArray();
        for (char index : chars) {
            if (currentTempNode.childrenNode[index] == null) {
                return false;
            }
            currentTempNode = currentTempNode.childrenNode[index];
        }
        return currentTempNode.isWord;
    }

    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        TrieNode currentTempNode = root;
        char[] chars = prefix.toCharArray();
        for (char index : chars) {
            if (currentTempNode.childrenNode[index] == null) {
                return false;
            }
            currentTempNode = currentTempNode.childrenNode[index];
        }
        return true;
    }
}
